class Solution
{
public:
    int minTime(int n, vector<vector<int>> &edges, vector<bool> &hasApple)
    {
        vector<vector<int>> adjTable(n);
        for (auto &edge : edges)
        {
            adjTable[edge[0]].push_back(edge[1]);
            adjTable[edge[1]].push_back(edge[0]);
        }
        vector<bool> visited(n, false);
        visited[0] = true;
        int result = 0;
        dfs(0, adjTable, visited, hasApple, result);
        return result;
    }

    bool dfs(int node, vector<vector<int>> &adjTable, vector<bool> &visited, vector<bool> &hasApple, int &result)
    {
        bool subHasApple = false;
        for (int adjNode : adjTable[node])
        {
            if (!visited[adjNode])
            {
                visited[adjNode] = true;
                if (dfs(adjNode, adjTable, visited, hasApple, result))
                {
                    subHasApple = true;
                    result += 2;
                }
            }
        }
        return subHasApple || hasApple[node];
    }
};